package cn.tml.innermost.user.utils;

import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.concurrent.TimeUnit;

/**
 * @author welsir
 * @version 1.0
 * @description: TODO
 * @date 2022/11/6 23:30
 */
@Service
public class RedisUtils {

    @Resource
    private RedisTemplate redisTemplate;

    private final Long defaultTime = 60*60*10000L;
    private final TimeUnit defaultTimeUnit = TimeUnit.MILLISECONDS;

    /**
     * @description:  写入缓存+过期时间
     * @param: [key, value, expireTime, timeUnit]
     * @return: [key, value, expireTime, timeUnit]
     * @author: WELSIR
     * @date: 2022/11/6 23:32
     */
    public boolean set(String key, String value, Long expireTime, TimeUnit timeUnit){
        redisTemplate.opsForValue().set(key,value);
        redisTemplate.expire(key,expireTime,timeUnit);
        return true;
    }

    public void set(String key, Object value, TimeUnit timeUnit){
        redisTemplate.opsForValue().set(key,value);
        redisTemplate.expire(key,defaultTime,timeUnit);
    }

    public void set(Long key, Object value){
        String redisKey = getRedisKey(key);
        redisTemplate.opsForValue().set(redisKey,value);
        redisTemplate.expire(redisKey,defaultTime,defaultTimeUnit);
    }

    /** 
     * @description:  通过key获取value
     * @param: [key]
     * @return: [key] 
     * @author: WELSIR
     * @date: 2022/11/6 23:34
     */ 
    public Object get(String key){
        return redisTemplate.opsForValue().get(key);
    }

    public void remove(final String ...key){
        for (String keys : key) {
            if (redisTemplate.hasKey(keys)) {
                redisTemplate.delete(keys);
            }
        }
    }

    public boolean remove(Long key){
        String redisKey = getRedisKey(key);
        if (redisTemplate.hasKey(redisKey)) {
            redisTemplate.delete(redisKey);
        }
        return true;
    }

    public String getRedisKey(Long oldKey){
        String newKey = "";
        Class<? extends Long> keyClass = oldKey.getClass();
        Field[] fields = keyClass.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                newKey+=(field.get(oldKey).toString());
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return newKey;
    }
}
